/*
 * Copyright (c) 2007
 *	Alberto Magni, Maggioni Marcello
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

package servlets;

import Database.UsersDB;
import beans.LoginBean;
import exceptions.DatabaseException;
import exceptions.LoginFailedException;
import java.io.*;
import java.net.*;

import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *  This servlet handles the Login request from the Login Page.
 * @author Marcello Maggioni
 */
public class LoginSrv extends HttpServlet {
   
    private UsersDB uf; 
    
    @Override
    public void init() throws ServletException  {
        super.init();
        uf = (UsersDB) this.getServletContext().getAttribute("usersdb");
    }
    
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    @SuppressWarnings("unchecked")
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            response.setContentType("text/html;charset=UTF-8");
            String username = (String) request.getParameter("username");
            String password = (String) request.getParameter("password");

            if (uf.verifyUser(username, password)) {
                LoginBean lb = new LoginBean();
                lb.setUsername(username);
                if (uf.isAdmin(username)) {
                    lb.setAdmin(true);
                }
                lb.setSessionid(request.getSession().getId());
                Map<String,String> usersmap = (Map<String,String>) getServletContext().getAttribute("usersmap");
                
                usersmap.put(username, lb.getSessionid());
                request.getSession().setAttribute("loggedin", lb);
                request.getRequestDispatcher("datainput.jsp").forward(request, response);
                return;
            }

            request.setAttribute("exception", new LoginFailedException("The login has failed. Check your username and password and try again."));
            request.getRequestDispatcher("error.jsp").forward(request, response);
        } catch (DatabaseException ex) {
            request.setAttribute("exception", ex);
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
